Decode Ways

A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.

题目大意:A -> Z 分别编码1->26,给定一串编码值,例如"12",可以解码为"AB"和"Z",共2种情况,返回解码方式的个数

题目难度:Medium

/**
 * Created by gzdaijie on 16/6/5
 * 0,30,40,50... => 0
 * 10,20 => f(n) = f(n-2)
 * <=9 || > 26 => f(n) = f(n -1)
 * 11 - 26 => f(n) = f(n-1) + f(n - 2)
 * 动态规划,时间复杂度O(N), 空间复杂度O(N)
 */
public class Solution {
    public int numDecodings(String s) {
        int len = s.length();
        if (len == 0 || s.charAt(0) == '0') return 0;

        int[] count = new int[len + 1];
        count[0] = count[1] = 1;
        for (int i = 1; i < len; i++) {
            int sum = (s.charAt(i - 1) - '0') * 10 + (s.charAt(i) - '0');
            if (sum % 10 == 0) {
                if(sum == 10 || sum == 20) count[i + 1] = count[i - 1];
                else return 0;
            }
            else if (sum < 10 || sum > 26) count[i + 1] = count[i];
            else count[i + 1] = count[i] + count[i - 1];
        }
        return count[len];
    }
}
gzdaijie            updated 2016-06-05 15:50:34

results matching ""

    No results matching ""